package cn.hdustea.shopNavigation.ui.view

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatEditText
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import cn.hdustea.shopNavigation.R
import cn.hdustea.shopNavigation.config.ConfigKey
import cn.hdustea.shopNavigation.interfaze.IKeyEvent
import cn.hdustea.shopNavigation.ui.view.main.MallSearchActivity
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.reflect.TypeToken
import com.iflytek.cloud.RecognizerResult
import com.iflytek.cloud.SpeechConstant
import com.iflytek.cloud.SpeechError
import com.iflytek.cloud.ui.RecognizerDialog
import com.iflytek.cloud.ui.RecognizerDialogListener
import kotlinx.android.synthetic.main.activity_search.*


class SearchActivity : AppCompatActivity() {
    private var iatDialog: RecognizerDialog? = null

    private val mSearchListener = object : IKeyEvent {
        override fun search(activity: AppCompatActivity) {
            val item = et_search_view.text.toString()
            saveItem(item)
            KeyboardUtils.hideSoftInput(activity)
            finish()
        }

    }

    companion object {
        fun startActivity(context: Context) {
            context.startActivity(Intent(context, SearchActivity::class.java))
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        initView()
        initVoice()
    }

    private fun initView() {
        val layoutManager = LinearLayoutManager(this)
        rv_search.layoutManager = layoutManager
        rv_search.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
        val searchHistoryAdapter = SearchHistoryAdapter(R.layout.item_list_search_history)
        rv_search.adapter = searchHistoryAdapter
        val history: MutableList<String>? = GsonUtils.fromJson(ConfigKey.getSearchHistory(),
                object : TypeToken<MutableList<String>>() {}.type)
        searchHistoryAdapter.setList(history)
        searchHistoryAdapter.addChildClickViewIds(R.id.img_delete_history_item)
        searchHistoryAdapter.setOnItemChildClickListener { adapter, _, position ->
            history?.remove(adapter.data[position])
            ConfigKey.setSearchHistory(GsonUtils.toJson(history))
            adapter.removeAt(position)
        }

        img_top_search.setOnClickListener {
            iatDialog!!.show()
        }

        tv_top_search.setOnClickListener {
            val data = et_search_view.text.toString()
            val intent = Intent(this, MallSearchActivity::class.java)
            intent.putExtra("extra_data", data)
            startActivity(intent)
//            Log.d("data", data)

            mSearchListener.search(this)
        }

        et_search_view.isFocusable = true
        et_search_view.isFocusableInTouchMode = true
        et_search_view.requestFocus()

    }

    private fun saveItem(item: String) {
        if (!StringUtils.isEmpty(item) && !StringUtils.isSpace(item)) {
            val history: MutableList<String>?
            val historyStr = ConfigKey.getSearchHistory()
            history = if (StringUtils.isEmpty(historyStr)) {
                mutableListOf()
            } else {
                GsonUtils.fromJson(historyStr,
                        object : TypeToken<MutableList<String>>() {}.type)
            }
            history!!.remove(item)
            if (history.size == 6) {
                history.removeLast()
            }
            history.add(0, item)
            val json = GsonUtils.toJson(history)
            ConfigKey.setSearchHistory(json)
        }
    }

    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is AppCompatEditText) {
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        return false
    }

    private fun initVoice() {
        iatDialog = RecognizerDialog(this) { }
        iatDialog!!.setParameter(SpeechConstant.RESULT_TYPE, "plain")
        iatDialog!!.setParameter(SpeechConstant.ASR_PTT, "0")
        iatDialog!!.setListener(object : RecognizerDialogListener {
            override fun onResult(recognizerResult: RecognizerResult, b: Boolean) {
                et_search_view.setText(et_search_view.text.toString() + recognizerResult.resultString)
            }

            override fun onError(speechError: SpeechError) {}
        })
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideInput(v, ev)) { //点击editText控件外部
                KeyboardUtils.hideSoftInput(v!!) //软键盘工具类
                et_search_view.clearFocus()
            }
            return super.dispatchTouchEvent(ev)
        }
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (event!!.keyCode == KeyEvent.KEYCODE_ENTER) {
            mSearchListener.search(this)
            return true
        }
        return super.dispatchKeyEvent(event)
    }

    inner class SearchHistoryAdapter(layoutRes: Int) :
            BaseQuickAdapter<String, BaseViewHolder>(layoutRes) {

        override fun convert(holder: BaseViewHolder, item: String) {
            holder.setText(R.id.tv_search_item_name, item)
        }

    }

}